package com.zb.cookie.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class CookieServlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        PrintWriter writer = resp.getWriter();

        Cookie[] cookies = req.getCookies();

        if(null != cookies && cookies.length > 0){
            List<Cookie> cookieList = Arrays.stream(cookies).filter((cookie) -> cookie.getName().equals("LastLoginTime")).collect(Collectors.toList());
            if(cookieList.size() == 0) {
                writer.println("您是第一次登录本网站！");
            }else{
                String lastLoginTime = cookieList.get(0).getValue();
                writer.println("您上次登录本网站的时间为：" + new Date(Long.parseLong(lastLoginTime)).toLocaleString());
            }
        }
        Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis() + "");
        //设置cookie存活时间，0代表立即删除此cookie，可以用于删除cookie操作
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
